<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import mcApi from 'mc-c2b2m-operator-api';
  import { ActionTypeEnum } from '@/enums/commonEnum';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useUserStore } from '@/store/modules/user';
  import { BasicForm, useForm } from '@/components/Form';
  import { modalFormSchema, permissionFormSchema } from './data';
  import { BasicModal, useModalInner } from '@/components/Modal';

  const { SystemModule } = mcApi;
  const { PositionApi } = SystemModule;
  const { ADD, EDIT, OTHER } = ActionTypeEnum;

  const [registerForm, { setFieldsValue, resetFields, validate, resetSchema, getFieldsValue }] =
    useForm({
      schemas: [],
      labelWidth: 100,
      baseColProps: { span: 22 },
      showActionButtonGroup: false,
    });

  const userStore = useUserStore();
  const userInfo = computed(() => {
    return userStore.getUserInfo || {};
  });

  const actionType = ref<number>(ADD);
  const titleObj = {
    [ADD]: '新增角色',
    [EDIT]: '编辑角色',
    [OTHER]: '分配权限',
  };
  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    await resetFields();
    actionType.value = Number(data.actionType);
    setModalProps({
      minHeight: 250,
      destroyOnClose: true,
      confirmLoading: false,
      title: titleObj[actionType.value],
    });
    await resetSchema(actionType.value === OTHER ? permissionFormSchema : modalFormSchema);
    if (actionType.value !== ADD) {
      const { record } = data;
      const { orgDeptId, orgDeptName } = record;
      orgDeptId && (record.orgDeptId = [{ label: orgDeptName, value: orgDeptId }]);
      await setFieldsValue({ ...record });
    }
  });

  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);
  const funObj = {
    [ADD]: PositionApi.createOrgPosition,
    [OTHER]: PositionApi.assignPermissionsToPosition,
  };
  async function handleOk() {
    try {
      await validate();
      const values: any = getFieldsValue();
      const { orgDeptId } = values;
      orgDeptId?.length && (values.orgDeptId = orgDeptId[0].value);
      values.orgId = userInfo.value.orgId;
      setModalProps({ confirmLoading: true });
      const fun = funObj[actionType.value];
      if (!fun) return;
      await fun(values);
      createMessage.success(`${titleObj[actionType.value]}成功！`);
      emits('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped lang="less"></style>
